package com.cygia.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cygia.common.Result;
import com.cygia.entity.Model;
import com.cygia.mapper.ModelMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/model")
public class ModelController {
    @Resource
    ModelMapper modelmapper;

    /**
     * 查询模块
     *
     * @param pageNum  第几页
     * @param pageSize 每页多少条
     * @param search   搜索名称
     * @return
     */
    @GetMapping("/pageModel")
    public Result<?> findPageModel(@RequestParam(defaultValue = "1") Integer pageNum,
                                  @RequestParam(defaultValue = "10") Integer pageSize,
                                  @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<Model> wrapper = Wrappers.<Model>lambdaQuery();
        if (!search.isEmpty() || search.length() > 0) {
            wrapper.like(Model::getModelname, search);
        }
        IPage page = modelmapper.selectPage(new Page(pageNum, pageSize), wrapper);

        List records = page.getRecords();
        System.out.println("--共"+page.getTotal()+"条\n--每页"+page.getSize()+"条\n--第"+page.getCurrent()+"页\n--查询到的数据：\n");
        for (int i= 0;i<records.size();i++) {
            System.out.println(records.get(i));
        }
        return Result.success(page);
    }

    /**
     * 添加or更新模块
     *
     * @param model
     * @return
     */
    @PostMapping("/saveModel")
    public Result<?> saveModel(@RequestBody Model model) {
        if (model == null) {
            return Result.error(-1, "创建模块不存在");
        }
        if (model.getId() == null || model.getId().equals("")) {
            Model res = modelmapper.selectOne(Wrappers.<Model>lambdaQuery().eq(Model::getModelname, model.getModelname()));
            if(res==null){
                modelmapper.insert(model);
                return Result.success(0, "添加模块成功!");
            }else{
                return Result.success(-1, "模块名称已存在!");
            }
        } else {
            modelmapper.updateById(model);
            return Result.success(1, "更新模块成功!");
        }
    }


    /**
     * 删除模块
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delModel/{id}")
    public Result<?> delModel(@PathVariable Integer id) {
        if (id != null) {
            modelmapper.deleteById(id);
            return Result.success(3, "删除模块成功！");
        } else {
            return Result.success(4, "删除模块失败！");
        }
    }

}
